<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Index_Product extends Controller_Index_Base
{    
    public function action_index()
    {
        $product_id = $this->request->param('id') ? $this->request->param('id') : 0;
        $url        = $this->request->param('url') ? $this->request->param('url') : 0;
        
        $product  = ORM::factory('product')->filter($product_id);
        if (Helper_Index::product_url($product) != '/product/'.$product_id.'-'.$url) {
            Helper_Index::redirect_301(Helper_Index::product_url($product));
        }
        $product_data = $product->get_product_data();
        
        $category = ORM::factory('category', $product->category_id);
        $shop     = ORM::factory('shop', $product->shop_id);
        
        $coupons     = ORM::factory('coupon')->get_coupons_by_product($product);
        $best_coupon = null;
         if (count($coupons)) {
            //$tmp_best_coupon = array_slice($coupons, 0, 1, true);    
            $array_keys = array_keys($coupons);
            $best_coupon = $coupons[$array_keys[0]]; 
        }
        
        $content = new View('index/product/index_tpl');
        $content->product  = $product;
        $content->product_data = $product_data;
        $content->specs    = $product->extract_specs($product_data);
        $content->category = $category;
        $content->shop     = $shop; 
        $content->breadcrumbs = $category->get_breadcrumbs();
        $content->coupons  = $coupons;
        $content->best_coupon = $best_coupon;
        $related_products = $product->get_related_products();
        $content->related_products = $related_products;
        $content->related_products_coupons = ORM::factory('coupon')->get_coupons_by_products($related_products);
        $content->related_products_shops   = ORM::factory('shop')->get_shops_by_products($related_products);
        
        $content->text = Helper_Index::get_product_index_text($product, $category, $best_coupon, $shop);
        
        $title       = Helper_Index::get_product_index_title($product, $product_data, $best_coupon, $shop); 
        $description = Helper_Index::get_product_index_description($product, $product_data, $best_coupon, $shop);
        $this->print_template($title, $content, $description); 
    }
    
    public function action_go()
    {
        $product_id = $this->request->param('product_id') ? $this->request->param('product_id') : 0;
        $product    = ORM::factory('product', $product_id);
        $shop       = ORM::factory('shop', $product->shop_id); 
        
        ORM::factory('click')->add_click_if_cashback_available($shop); 
        
        $content = new View('index/product/go_tpl');
        $content->title   = 'Осуществляется переход...';
        $content->product = $product;
        $content->shop    = $shop;
        $content->delay   = 2;       
        $this->response->body($content);
    }
} 
